<template>
  <view class="content">
    <img :src="avatarUrl || '../../static/tx.jpg'" alt="用户头像" mode="aspectFill" class="pic" @click="choosepic()">
    <view class="info">
      <view>
        <text class="required">*</text>姓名
        <input type="text" placeholder="请输入姓名" v-model="nickName" :class="{'error': !nickName && formSubmitted}"/>
      </view>
      <view>
        <text class="required">*</text>联系方式
        <input type="text" placeholder="请输入联系方式" v-model="phone" :class="{'error': !phone && formSubmitted}"/>
      </view>
      <view>
        <text class="required">*</text>身份证号码
        <input type="text" placeholder="请输入身份证号码" v-model="idCard" :class="{'error': !idCard && formSubmitted}"/>
      </view>
      <view>
        <text class="required">*</text>工作单位
        <input type="text" placeholder="请输入工作单位" v-model="unit" :class="{'error': !unit && formSubmitted}"/>
      </view>
    </view>
    <view class="agree">
      <view class="custom-checkbox" style="float: left;"
        :class="{'agreed-bg':isAgreed, 'error': !isAgreed && formSubmitted}"
        @click="toggleAgree">
        <icon 
          :type="isAgreed ? 'success_circle' : 'circle'" 
          :color="isAgreed ? '#09BB07' : '#999'" 
          size="16"
        />
      </view>
      <text>我已同意并阅读<text @click="contract()" class="dh">《用户协议》</text></text>
    </view>
    <button class="login_button" @click="login()" :loading="loading">立即登录</button>
  </view>
</template>

<script>
import { login, autoLogin, getUserAvatar } from '/api/request.js';
import { ByPhone } from '@/api/userApi.js';
export default {
  data() {
    return {
      title: 'Hello',
      isAgreed: false,
      nickName: '',
      phone: '',
      idCard: '',
      unit: '',
      avatarUrl: '', // 确保包含头像URL
      loading: false,
      formSubmitted: false
    }
  },
  onLoad() {
	
    const token = uni.getStorageSync('token');
    if (token) {
      uni.navigateTo({ url: '/pages/main/main' });
    }
  },
  methods: {
    toggleAgree() {
      this.isAgreed = !this.isAgreed;
    },
    validateForm() {
      this.formSubmitted = true;
      if (!this.nickName || !this.phone || !this.idCard || !this.unit) {
        return false;
      }

      const phoneRegex = /^\d{11}$/;
      if (!phoneRegex.test(this.phone)) {
        this.showToast('请输入正确的11位手机号码', 'none');
        return false;
      }

      const idCardRegex = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
      if (!idCardRegex.test(this.idCard)) {
        this.showToast('请输入正确的身份证号码', 'none');
        return false;
      }

      if (!this.isAgreed) {
        this.showToast('请同意用户协议', 'none');
        return false;
      }

      return true;
    },
    async login() {
      // 1. 启用表单验证
      // if (!this.validateForm()) return;
	  this.nickName='刘希言'
	  this.phone='18671196045'
	  this.idCard='420324200211031010'
	  this.unit='xxxc'
	  this.avatarUrl='http://tmp/lNqnr3ZkHmnwb5e3cd896e3efcc9cbad755870f1f61d.jpg'
	  // this.nickName='rose'
	  // this.phone='12584748575'
	  // this.idCard='420281199510250818'
	  // this.unit='YG'
	  // this.avatarUrl='http://tmp/GStEUHSldVt7e093a1bfaa526f82f59b787c56c9d721.png'
      
      // 2. 准备完整登录数据（包含头像）
      const loginData = {
        nickName: this.nickName,
        phone: this.phone,
        idCard: this.idCard,
        unit: this.unit,
        avatarUrl: this.avatarUrl // 确保包含头像URL
      };
      
      console.log('发送的登录数据:', loginData);
      
      // this.loading = true;
      
      try {
        // 3. 发送登录请求
        let res = await login(loginData);
		uni.setStorageSync('user', loginData);
        
        // 4. 确保响应包含完整的用户数据
        if (res.data && res.data.user) {
          console.log('后端返回的用户数据:', res.data.user);
          	 
          // 5. 存储完整用户信息
          uni.setStorageSync('userInfo', res.data.user);
          uni.setStorageSync('token', res.data.token);
          
          // 6. 更新本地头像URL（确保一致性）
          this.avatarUrl = res.data.user.avatarUrl || this.avatarUrl;
          
          uni.switchTab({
            url: '/pages/main/main'
          });
		  this.fetchUserByPhone();
        } else {
          console.error('响应缺少user对象', res);
          this.showToast('登录失败：缺少用户信息', 'none');
        }
      } catch (error) {
        console.error('登录失败:', error);
        this.showToast('登录失败: ' + (error.message || '未知错误'), 'none');
      } finally {
        this.loading = false;
      }
    },
    async choosepic() {
      try {
        const res = await uni.chooseImage({
          count: 1,
          sizeType: ['compressed'],
          sourceType: ['album', 'camera']
        });
        this.avatarUrl = res.tempFilePaths[0];
        
        // 上传头像并获取服务器URL
        const serverUrl = await this.uploadAvatar(this.avatarUrl);
        this.avatarUrl = serverUrl; // 更新为服务器返回的URL
      } catch (err) {
        console.error('选择头像失败:', err);
        this.showToast('选择头像失败', 'none');
      }
    },
	fetchUserByPhone() {
	  if (!this.phone) {
	    console.error("phone为空，无法请求");
	    uni.showToast({ title: '手机号未获取到', icon: 'none' });
	    return;
	  }
				 
	  ByPhone(this.phone)
	    .then(res => {
	      if (res.code == '200' && res.data) {
	        console.log('已更新缓存用户信息:', res.data);
			uni.setStorageSync('user', res.data);
	      } else {
	        uni.showToast({ title: '未找到用户数据', icon: 'none' });
	      }
	    })
	    .catch(error => {
	      uni.showToast({ title: '请求失败', icon: 'none' });
	      console.error('请求失败:', error);
	    });
	},
    uploadAvatar(filePath) {
      return new Promise((resolve, reject) => {
        uni.showLoading({ title: '上传中...' });
        uni.uploadFile({
          url: 'https://tcb-api.tencentcloudapi.com/upload', // 替换为实际API
          filePath: filePath,
          name: 'avatar',
          success: (res) => {
            uni.hideLoading();
            
            try {
              // 解析服务器响应（假设返回JSON）
              const data = JSON.parse(res.data);
              
              if (data.code === 200 && data.data.url) {
                uni.showToast({ title: '上传成功' });
                resolve(data.data.url); // 返回服务器上的URL
              } else {
                reject(new Error(data.message || '上传失败'));
              }
            } catch (e) {
              reject(new Error('解析响应失败'));
            }
          },
          fail: (err) => {
            uni.hideLoading();
            reject(err);
          }
        });
      });
    },
    showToast(title, icon) {
      uni.showToast({
        title,
        icon,
        duration: 2000
      });
    },
    showModal(title, content, confirmCallback) {
      uni.showModal({
        title,
        content,
        showCancel: false,
        confirmText: '确定',
        confirmColor: '#F8900D',
        success: (res) => {
          if (res.confirm && confirmCallback) {
            confirmCallback();
          }
        }
      });
    }
  }
}
</script>

<style>
.content{
	position: relative;
}
.content .login{
	text-align: center;
}
.content .pic{
	position: absolute;
	width: 150px;
	height: 150px;
	left: 120px;
	top: 30px;
	border-radius: 150px;
}
.content .info{
	position: absolute;
	top: 210px;
	left: 30px;
}
.content .info view{
	margin-bottom: 10px;
}
.content .info view input{
	border: 1px solid #F6F6F6;
	width: 300px;
	padding: 2px;
	margin: 5px;
	border-radius: 5px;
	background-color: #F6F6F6;
	
}
.content .info view text{
	color: red;
}
.content .agree{
	position: absolute;
	top: 500px;
	left: 30px;
}
.agree .dh{
	color: #FA816B;
	float: right;
}
.content .login_button{
	position: absolute;
	top: 550px;
	left: 50px;
	width: 240px;
	height: 55px;
	line-height: 55px;
	background: linear-gradient(to right,#F8900D,#FD623C);
	border-radius: 50px;
	color: white;
	font-size: 15px;
	font-weight: 700;
	font-family: 'Gill Sans', 'Gill Sans MT', Calibri, 'Trebuchet MS', sans-serif;
}
.custom-checkbox .agreed-bg{
	background-color: #FA6146;
}

</style>